package middleware

import (
	"ginadmin/app/dao"
	"ginadmin/app/model"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

// 后台中间件
func AdminMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {

		session := sessions.Default(c)

		adminId := session.Get("adminId")

		errCode := 0

		if adminId == nil || adminId == 0 {
			c.Abort()
			c.Redirect(302, "/admin/login")
		} else {
			//验证权限
			var admin model.AdminUser
			admin.ID = adminId.(uint)
			dao.DB.First(&admin)

			if admin.ID == 0 || !admin.Status {

				c.Abort()
				c.JSON(200, gin.H{
					"code": errCode,
					"msg":  "账号不存在或被禁用",
				})

			} else {

				path := c.Request.URL.Path
				//继续验证权限
				res := model.AuthCheck(path, admin.Roles)

				if !res {
					c.Abort()
					c.JSON(200, gin.H{
						"code": errCode,
						"msg":  "无权操作",
					})
				} else {
					c.Set("adminId", adminId)
					c.Set("adminRoles", admin.Roles)
				}
			}
		}

		//c.Next()
		//终止后续方法执行，但中间件后面的内容会继续执行
		//c.Abort()
	}
}
